<template>
  <div class="register">
    <h1>注册</h1>
    <el-form :model="form" :rules="rules" ref="registerForm">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="full_name" label="姓名">
        <el-input v-model="form.full_name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();
const registerForm = ref();
const form = ref({
  username: '',
  full_name: '',
  email: '',
  password: ''
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  full_name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const handleRegister = async () => {
  try {
    await registerForm.value.validate();
    await userStore.register(form.value);
    ElMessage.success('注册成功');
    router.push('/login');
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error('注册失败: ' + (error.response?.data?.detail || '未知错误'));
  }
};
</script>